import axios from 'axios';
import { Message } from 'element-ui';
import router from '../router/index'

const service = axios.create({
  timeout: 30000
});
service.defaults.withCredentials = true;
service.defaults.headers.post['Content-Type'] = 'application/json';

//TODO 注意
//本地测试需要注释掉这个方法,打包到eclipse时打开
// service.interceptors.request.use(config => {
//   let realUrl = config.url.replace('api/', '');
//   //console.log(realUrl);
//   config.url = realUrl;
//   //console.log(config);
//   return config;
//   //只针对get方式进行序列化
//   // if (config.method === 'get') {
//   //   config.paramsSerializer = function (params) {
//   //     return qs.stringify(params, { arrayFormat: 'repeat' })
//   //   }
//   // }
// });
service.interceptors.response.use(

  response => {
    if (response.status === 200) {
      return response;
    } else {
      Message({
        message: `${response.status} - ${response.data ? response.data : response.statusText}`,
        type: 'warning'
      });
      return response
    }
  },
  error => {
    if(error.message.includes('timeout')){
      Message({
        message: '访问超时，请重试!',
        type: 'warning'
      });
    } else if (error.response.status === 401) {
      localStorage.removeItem('token');
      router.push("/")
    } else if (error.response.status === 405) {
      router.push("/")
    } else if (error.response.status === 502) {
      Message({
        message: '与服务器连接超时!',
        type: 'error'
      });
    }else if (error.response.status === 504) {
      Message({
        message: '与服务器连接断开!',
        type: 'error'
      });
    } else {
      console.log(error.response);
      Message({
        message: `${error.response.status} - ${error.response.data ? error.response.data : error.response.statusText}`,
        type: 'error'
      });
    }
    return Promise.reject(error);
  }
);

export default service;